import axios, {AxiosInstance, AxiosRequestConfig, AxiosResponse, InternalAxiosRequestConfig} from 'axios'
import {HttpType} from '@/type/httpType'
import {ElNotification } from 'element-plus'


class Http {
  private instance: AxiosInstance;

  constructor(config: AxiosRequestConfig) {
    this.instance = axios.create(config);
    this.interceptors()
  }

  private interceptors () {
    // 请求拦截器
    this.instance.interceptors.request.use((config: InternalAxiosRequestConfig) => {
      const token = sessionStorage.getItem("token")!
      if (token) {
        // Authorization
        config.headers["token"] = token
      }
      return config
    }, error => {
      return error
    })
    // 响应拦截器
    this.instance.interceptors.response.use((config:AxiosResponse) => {
      if (config.data.code === 200) {
        return config.data
      }
      ElNotification({
        title: 'Error',
        message: config.data.msg,
        type: 'error',
      })
      return Promise.reject(config.data)
    }, error => {
      return error
    })
  }

  public get<T = any>(url: string, params?: unknown): Promise<HttpType<T>> {
    return this.instance.get(url, {params})
  }

  public post<T = any>(url: string, data?: unknown): Promise<HttpType<T>> {
    return this.instance.post(url, data)
  }

  public put<T = any>(url: string, data?: unknown): Promise<HttpType<T>> {
    return this.instance.put(url, data)
  }

  public delete<T = any>(url: string, params?: unknown): Promise<HttpType<T>> {
    return this.instance.delete(url, {params})
  }
}

const http = new Http({
  baseURL: window.CONFIG.baseURL,
})

export default http
